package com.example.yimai.service.impl;

import com.example.yimai.entity.FavoriteCollect;
import com.example.yimai.entity.FavoriteItem;
import com.example.yimai.entity.Product;
import com.example.yimai.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class FavoriteService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ProductMapper productMapper;

    private static final String COLLECT_KEY_PREFIX = "collects:";

    public String addToCollect(String userId, String productId, String collectId) {
        try {
            String redisKey = COLLECT_KEY_PREFIX + userId;
            FavoriteCollect favoriteCollect = (FavoriteCollect) redisTemplate.opsForHash().get(redisKey, collectId);
            if (favoriteCollect == null)throw new RuntimeException("收藏夹不存在");
            FavoriteItem favoriteItem = new FavoriteItem();
            favoriteItem.setCollectId(collectId);
            favoriteItem.setProductId(productId);
            Product product = productMapper.selectById(productId);
            favoriteItem.setProductName(product.getName());
            favoriteItem.setProductImage(product.getFileName());
            favoriteCollect.getFavoriteItems().add(favoriteItem);
            redisTemplate.opsForHash().put(redisKey, collectId, favoriteCollect);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("添加到收藏失败");
        }
    }

    public List<FavoriteItem> getCollectItems(String userId, String collectId) {
        try {
            String redisKey = COLLECT_KEY_PREFIX + userId;
            FavoriteCollect favoriteCollect = (FavoriteCollect) redisTemplate.opsForHash().get(redisKey, collectId);
            if (favoriteCollect == null)throw new RuntimeException("收藏夹不存在");
            return favoriteCollect.getFavoriteItems();
        }catch (Exception e){
            throw new RuntimeException("获取收藏商品失败");
        }
    }

    public List<FavoriteCollect> getCollects(String userId) {
        try {
            String redisKey = COLLECT_KEY_PREFIX + userId;
            // 检查Redis中是否存在该用户的收藏夹数据
            if (!redisTemplate.hasKey(redisKey)) {
                // 如果不存在，创建一个空的收藏夹
                FavoriteCollect defaultCollect = new FavoriteCollect();
                String collectId = UUID.randomUUID().toString();
                defaultCollect.setId(collectId);
                defaultCollect.setUserId(userId);
                defaultCollect.setName("默认收藏夹");
                defaultCollect.setFavoriteItems(new ArrayList<>());
                redisTemplate.opsForHash().put(redisKey, collectId, defaultCollect);
            }
            
            List<FavoriteCollect> collects = redisTemplate.opsForHash().values(redisKey).stream()
                .map(item -> {
                    if (item instanceof FavoriteCollect) {
                        return (FavoriteCollect) item;
                    } else {
                        // 如果类型不匹配，返回null
                        return null;
                    }
                })
                .filter(item -> item != null) // 过滤掉null值
                .toList();
            return collects;
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细错误信息
            // 如果出现异常，返回一个空列表而不是抛出异常
            return new ArrayList<>();
        }
    }

    public String removeFromCollect(String userId, String productId, String collectId) {
        try {
            String redisKey = COLLECT_KEY_PREFIX + userId;
            FavoriteCollect favoriteCollect = (FavoriteCollect) redisTemplate.opsForHash().get(redisKey, collectId);
            if (favoriteCollect == null) throw new RuntimeException("收藏夹不存在");
            favoriteCollect.getFavoriteItems().removeIf(item -> item.getProductId().equals(productId));
            redisTemplate.opsForHash().put(redisKey, collectId, favoriteCollect);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("从收藏夹中删除商品失败");
        }
    }

    public String createCollect(String userId, String name) {
        try {
            String redisKey = COLLECT_KEY_PREFIX + userId;
            FavoriteCollect favoriteCollect = new FavoriteCollect();
            String collectId = UUID.randomUUID().toString();
            favoriteCollect.setId(collectId);
            favoriteCollect.setUserId(userId);
            favoriteCollect.setName(name);
            redisTemplate.opsForHash().put(redisKey, collectId, favoriteCollect);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("创建收藏夹失败");
        }
    }

    public String removeCollect(String userId, String collectId) {
        try {
            String redisKey = COLLECT_KEY_PREFIX + userId;
            redisTemplate.opsForHash().delete(redisKey, collectId);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("删除收藏夹失败");
        }
    }

}
